<style scoped>
  .comn >>> .el-form-item__content {
    width: 170px;
  }
  .app-container >>> .scode {
    cursor: pointer;
    color: #20B2AA;
    text-decoration: underline;
  }
  .app-container >>> .scodeth {
    color: #515a6e;
  }
  .app-container >>> .address .cell {
    text-overflow: ellipsis;
    overflow: hidden;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
</style>
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="销售单号" prop="sellcode">
          <el-input
            v-model="queryParams.search"
            placeholder="请输入销售单号"
            clearable
            size="mini"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      <el-form-item label="客户" prop="customerguid">
        <el-select v-model="queryParams.customerguid" placeholder="请选择客户" filterable clearable size="mini">
          <el-option
            v-for="item in customers"
            :key="item.guid"
            :label="item.name"
            :value="item.guid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="depguid">
        <el-select v-model="queryParams.depguid" placeholder="请选择部门" filterable clearable size="mini">
          <el-option
            v-for="item in departments"
            :key="item.guid"
            :label="item.name"
            :value="item.guid"
          />
        </el-select>
      </el-form-item>
        <el-form-item label="产品">
          <el-select v-model="queryParams.productguid" placeholder="请选择产品" filterable clearable size="mini">
            <el-option
              v-for="item in productOptions"
              :key="item.guid"
              :label="item.productname"
              :value="item.guid"
              @click.native="getSp($event, item)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="spguid">
          <el-select v-model="queryParams.spguid" placeholder="请选择规格" filterable clearable size="mini">
            <el-option
              v-for="item in spOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库房" prop="storermguid">
          <el-select v-model="queryParams.storermguid" placeholder="请选择库房" filterable clearable size="mini">
            <el-option
              v-for="item in roomOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="付款方式" prop="paytype">
          <el-select v-model="queryParams.paytype" placeholder="请选择付款方式" clearable size="mini">
            <el-option
              v-for="dict in sellpaytypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" filterable clearable size="mini">
            <el-option
              v-for="dict in stats"
              :key="dict.dictkey"
              :label="dict.dicttext"
              :value="dict.dictkey"
            />
          </el-select>
        </el-form-item>
        <!--      <el-form-item label="销售人员" prop="operatorid">-->
        <!--        <el-select v-model="queryParams.operatorid" placeholder="请选择种植户" size="small">-->
        <!--          <el-option-->
        <!--            v-for="item in salers"-->
        <!--            :key="item.id"-->
        <!--            :label="item.realname"-->
        <!--            :value="item.guid"-->
        <!--          />-->
        <!--        </el-select>-->
        <!--      </el-form-item>-->
      <el-form-item label="下单时间">
        <el-date-picker
          v-model="dateRange"
          size="mini"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结算时间">
        <el-date-picker
          v-model="dateRangeSettl"
          size="mini"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始结算日期"
          end-placeholder="结束结算日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="出库时间">
        <el-date-picker
          v-model="dateRangeWhout"
          size="mini"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始出库日期"
          end-placeholder="结束出库日期"
        ></el-date-picker>
      </el-form-item>
      <br/>
      <div>
          <el-form-item label="汇总: " prop="depcondition">
            <el-checkbox-group v-model="queryParams.depcondition">
              <el-checkbox v-for="(item, index) in depconditionOptions" :key="index" :label="item.value" :true-label="item.value" :false-label="''">{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="" prop="applycondition">
            <el-checkbox-group v-model="queryParams.applycondition">
              <el-checkbox v-for="(item, index) in applyconditionOptions" :key="index" :label="item.value" :true-label="item.value" :false-label="''">{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="" prop="srcondition">
            <el-checkbox-group v-model="queryParams.srcondition">
              <el-checkbox v-for="(item, index) in srconditionOptions" :key="index" :label="item.value" :true-label="item.value" :false-label="''">{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="" prop="customercondition">
            <el-checkbox-group v-model="queryParams.customercondition">
              <el-checkbox v-for="(item, index) in customerconditionOptions" :key="index" :label="item.value" :true-label="item.value" :false-label="''">{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="" prop="ordercondition">
            <el-select v-model="queryParams.ordercondition" placeholder="请选择产品或规格" clearable :style="{width: '100%'}">
              <el-option v-for="(item, index) in field103Options" :key="index" :label="item.label"
                         :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>

        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </div>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bill:sellform:export']"
        >导出
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          icon="el-icon-printer"-->
<!--          size="mini"-->
<!--          :disabled="ids.length != 1"-->
<!--          @click="handleWhinformExport"-->
<!--        >打印出库单</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="sellformList.length != 0 && sellformList[0].sellcode !== null" v-loading="loading" :data="sellformList" border :span-method="objectSpanMethod" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="销售单号" align="center" prop="sellcode" label-class-name="scodeth" class-name="scode">
          <template slot-scope="scope">
            <span @click="viewIt(scope.row.id)">{{ scope.row.sellcode }}</span>
<!--            <span>{{ scope.row.sellcode }}</span>-->
          </template>
        </el-table-column>
        <el-table-column label="订单时间" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" prop="statusname"/>
        <el-table-column label="销售部门" align="center" prop="depname"/>
        <el-table-column label="销售人员" align="center" prop="applyname"/>
        <el-table-column label="客户名称" align="center" prop="customername"/>
        <el-table-column label="联系电话" align="center" prop="customerphone"/>
        <el-table-column label="计价方式" align="center" prop="settletypename"/>
        <el-table-column label="支付方式" align="center" prop="paytypename"/>
        <el-table-column label="出库库房" align="center" prop="storeroomname"/>
<!--        <el-table-column label="出库重量" align="center" prop="loadweight"/>-->
        <el-table-column label="出库时间" align="center" prop="outtime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.outtime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="到货重量" align="center" prop="unnloadweight"/>
        <el-table-column label="结算金额" align="center" prop="finalamount"/>
        <el-table-column label="结算时间" align="center" prop="settletime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.settletime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="退换货" align="center" prop="withdrawtypename"/>
        <el-table-column label="品种" align="center" prop="productname"/>
        <el-table-column label="规格" align="center" prop="spname" />
        <el-table-column label="出库重量" align="center" prop="siloadweihgt"/>
        <el-table-column label="结算重量" align="center" prop="siunloadweight"/>
        <el-table-column label="单位" align="center" prop="stockunit"/>
        <el-table-column label="订单数量" align="center" prop="orderpack"/>
        <el-table-column label="赠送数量" align="center" prop="handselcount"/>
        <el-table-column label="结算数量" align="center" prop="sisettlecount"/>
        <el-table-column label="单位" align="center" prop="unit"/>
        <el-table-column label="单价" align="center" prop="price"/>
        <el-table-column label="结算金额" align="center" prop="sifinalamount"/>
        <el-table-column label="回款金额" align="center" prop="backmoney"/>
        <el-table-column label="收货地址" align="center" prop="maxdeduct" class-name="address">
          <template slot-scope="scope">
            <span>{{ scope.row.arriprovince }}{{ scope.row.arricity }}{{ scope.row.arridistrict }}{{ scope.row.arriaddres }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收货人" align="center" prop="contractid">
          <template slot-scope="scope">
            <span> {{ scope.row.arricontact }}[{{ scope.row.arricontactno }}]</span>
          </template>
        </el-table-column>
        <el-table-column label="运输车牌号" align="center" prop="carcode"/>
        <el-table-column label="备注" align="center" prop="remarks" :show-overflow-tooltip="true" />
      </el-table>
    <el-table  v-else v-loading="loading" :data="sellformList" border >
        <el-table-column v-if="sellformList.length != 0 && sellformList[0].depname !== null" label="销售部门" align="center" prop="depname"/>
        <el-table-column v-if="sellformList.length != 0 && sellformList[0].applyname !== null" label="销售人员" align="center" prop="applyname"/>
        <el-table-column v-if="sellformList.length != 0 && sellformList[0].storeroomname !== null" label="出库库房" align="center" prop="storeroomname"/>
      <el-table-column v-if="sellformList.length != 0 && sellformList[0].customername !== null" label="客户名称" align="center" prop="customername"/>
      <el-table-column v-if="sellformList.length != 0 && sellformList[0].customerphone !== null" label="联系电话" align="center" prop="customerphone"/>
      <el-table-column v-if="sellformList.length != 0 && sellformList[0].productname !== null" label="品种" align="center" prop="productname"/>
        <el-table-column v-if="sellformList.length != 0 && sellformList[0].spname !== null" label="规格" align="center" prop="spname" />
<!--      <el-table-column label="出库重量" align="center" prop="siunloadweight"/>-->

      <el-table-column v-if="sellformList.length != 0 && sellformList[0].siloadweihgt !== null" label="出库重量" align="center" prop="siloadweihgt"/>
        <el-table-column v-if="sellformList.length != 0 && sellformList[0].siunloadweight !== null" label="结算重量" align="center" prop="siunloadweight"/>
<!--        <el-table-column v-if="sellformList.length != 0 && sellformList[0].siunloadweight !== null" label="结算重量" align="center" prop="siunloadweight"/>-->
        <el-table-column v-if="sellformList.length != 0 && sellformList[0].sifinalamount !== null" label="结算金额" align="center" prop="sifinalamount"/>
      </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
  import { treeselect } from "@/api/system/dept";
  import {listSellform, getSellform, exportSellform, rptSellForm} from "@/api/bill/sellform";
  import {listDept} from "@/api/system/employee";
  import {listCustomer} from "@/api/customer/customer";
  import {findProductList, findSpecificationList, findStoreroom} from "@/api/public";
  import {getDicts} from "@/api/system/dict/data";
  import { getOldDicts } from "@/api/system/dict/data";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import Cookies from "js-cookie";

  export default {
    name: "Sellform1",
    components: { Treeselect },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 销售报表表格数据
        sellformList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          sellcode: null,
          search: null,
          depguid: null,
          customerguid: null,
          productguid:null,
          spguid: null,
          storermguid: null,
          status: null,
          createtime: null,
          operatorid: null,
          paytype: null,
          starttime: "",
          endtime: "",
          applycondition: "",
          depcondition: "",
          customercondition: "",
          srcondition: "",
          ordercondition: "",
        },
        // 表单参数
        form: {},
        departments: [],
        customers: [],
        roomOptions: [],
        stats: [],
        dateRange: [],
        dateRangeSettl: [],
        dateRangeWhout: [],
        sellpaytypeOptions: [],
        productOptions: [],
        spOptions: [],
        depconditionOptions: [{
          "label": "销售部门",
          "value": "depart"
        }],
        applyconditionOptions: [{
          "label": "销售人员",
          "value": "apply"
        }],
        srconditionOptions: [{
          "label": "库房",
          "value": "sr"
        }],
        customerconditionOptions: [{
          "label": "客户",
          "value": "customer"
        }],
        field103Options: [{
          "label": "产品",
          "value": "product"
        }, {
          "label": "规格",
          "value": "sp"
        }],
        spParams: {productguid: null,},
        printUrl: 'http://testadmin.tudouji.com.cn:8095/RDP-SERVER/rdppage/main/981883be22201ba17fd36761b6834914?sellcode=',
        deptOptions: [],
      };
    },
    created() {
      this.getDeparts();
      this.getCustomers();
      this.findProductList();
      this.findStoreroom();
      this.getDicts("pay_type").then(response => {
        this.sellpaytypeOptions = response.data;
      });
      // this.getDicts('sellform_status').then(response => {
      //   this.stats = response.data;
      // });
      getOldDicts({dicttype:17}).then(response => {
        this.stats = response.data;
      });
      //初始化下单时间
      let firDate = this.getNowMonthDate().join('-');
      let curDate = this.getDate(0).join('-');
      this.dateRange = [firDate, curDate];
      console.log('this.dateRange:', this.dateRange)
      this.getList();
    },
    methods: {
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.sellcode)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 打印按钮操作 */
      handleWhinformExport() {
        console.log('Cookies.get("username"):', Cookies.get("username"))
        let that = this;
        const autoid = this.ids[0];
        if (autoid) {
          window.open(that.printUrl + autoid + '&operator=' + Cookies.get("username"), "_blank", "toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
        }
      },
      //获取当前日期
      getDate: function (dayCount = 0) {
        var dd = new Date();
        dd.setDate(dd.getDate()+dayCount);//设置日期
        var y = dd.getFullYear();
        var m = dd.getMonth() + 1;//获取当前月份的日期
        var fullM = m.toString().length == 2 ? m : '0' + m;
        var d = dd.getDate();
        // return y+"-"+fullM+"-"+d;
        return [y, fullM, d];
      },
      //获取本月第一天
      getNowMonthDate: function () {
        var date = new Date();
        var year = date.getFullYear() + "";
        var month = date.getMonth() + 1 + "";
        // 本月第一天日期
        // var begin = year + "-" + month + "-01"
        return [year, month, "01"];
      },
      /** 查询销售报表列表 */
      getList() {
        this.loading = true;
        this.addDateRange(this.queryParams, this.dateRange);
        this.addRangeSettl(this.queryParams, this.dateRangeSettl);
        this.addRangeWhout(this.queryParams, this.dateRangeWhout);
        rptSellForm(this.queryParams).then(response => {
          this.sellformList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.gatherTableData();
        });
      },
      viewIt(id) {
        // this.$store.dispatch('tagsView/addVisitedView', 'sellforminfo');
        this.$router.push({path: '/bill/sellforminfo', query: {id: id}});
      },
      addRangeSettl(params, dateRange) {
        var search = params;
        search.startsettletime = "";
        search.endsettletime = "";
        if (null != dateRange && '' != dateRange) {
          search.startsettletime = dateRange[0];
          search.endsettletime = dateRange[1];
        }
        return search;
      },
      addRangeWhout(params, dateRange) {
        var search = params;
        search.startouttime = "";
        search.endouttime = "";
        if (null != dateRange && '' != dateRange) {
          search.startouttime = dateRange[0];
          search.endouttime = dateRange[1];
        }
        return search;
      },
      getSp(event, item) {
        this.spParams.productguid = item.guid;
        this.findSpecificationList();
      },
      findSpecificationList(){
        findSpecificationList(this.spParams).then(response => {
          this.spOptions = response.data;
        });
      },
      findProductList() {
        findProductList().then(response => {
          this.productOptions = response.data;
        });
      },
      findStoreroom() {
        findStoreroom().then(response => {
          this.roomOptions = response.data;
        });
      },
      getCustomers() {
        listCustomer().then(response => {
          this.customers = response.rows;
        });
      },
      getDeparts() {
        listDept().then(response => {
          this.departments = response.data;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          autoid: null,
          guid: null,
          flowtempguid: null,
          sellcode: null,
          applyname: null,
          depguid: null,
          depname: null,
          porgname: null,
          sorgguid: null,
          customerguid: null,
          customername: null,
          orderweight: null,
          storermguid: null,
          loadweight: null,
          unnloadweight: null,
          packweight: null,
          amount: null,
          finalamount: null,
          status: null,
          createtime: null,
          remarks: null,
          operatorid: null,
          quitsrtype: null,
          settletype: null,
          settlebilling: null,
          settledays: null,
          loadcount: null,
          unloadcount: null,
          concessiontype: null,
          maxdeduct: null,
          contractid: null,
          contractcode: null,
          contractname: null,
          paytype: null,
          currency: null,
          flag: null,
          parentcode: null,
          parentguid: null,
          lbweight: null,
          qaresult: null,
          finalweight: null,
          finalcount: null,
          backmoneytime: null,
          deliverytype: null,
          orderpack: null,
          backmoney: null,
          handselcount: null,
          handselweight: null,
          transferguid: null,
          settletime: null,
          withdrawtype: null,
          transtype: null,
          type: null,
          partitionflag: null,
          deductamount: null,
          senddate: null,
          arrivedate: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        console.log('this.dateRange:', this.dateRange)
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.autoid != null) {
              updateSellform(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addSellform(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有销售报表数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportSellform(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      // 获取相同编号的订单
      gatherTableData() {
        let OrderObj = {}
        this.sellformList.forEach((element, index) => {
          element.rowIndex = index
          if (OrderObj[element.sellcode]) {
            OrderObj[element.sellcode].push(index)
          } else {
            OrderObj[element.sellcode] = []
            OrderObj[element.sellcode].push(index)
          }
        })

        // 将数组长度大于1的值 存储到this.OrderIndexArr（也就是需要合并的项）
        this.OrderIndexArr = [];
        for (let k in OrderObj) {
          if (OrderObj[k].length > 1) {
            this.OrderIndexArr.push(OrderObj[k])
          }
        }
      },
      // 合并单元格
      objectSpanMethod({row,column,rowIndex,columnIndex}) {
        let colIndexs = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,27,28,29,30];
        if (colIndexs.indexOf(columnIndex) > -1) {
          for (let i = 0; i < this.OrderIndexArr.length; i++) {
            let element = this.OrderIndexArr[i]
            for (let j = 0; j < element.length; j++) {
              let item = element[j]
              if (rowIndex == item) {
                if (j == 0) {
                  return {
                    rowspan: element.length,
                    colspan: 1
                  }
                } else if (j != 0) {
                  return {
                    rowspan: 0,
                    colspan: 0
                  }
                }
              }
            }
          }
        }
      }
    }
  };
</script>
